﻿namespace LdtJudge.DataEngine.Data
{
    using System;
    using System.Data;
    using System.Reflection;




    ///<summary>
    /// 类名称  : SqlComDataHandle
    /// 功能    : 通用数据得层数据处理类
    /// 更新人  : ljx 
    ///</summary> 

    public class SqlComDataHandle
    {

        /// <summary>
        /// DataRow 转实体对象
        /// </summary>
        /// <typeparam name="T">实体</typeparam>
        /// <param name="row">行数据</param>
        /// <returns></returns>
        public T GetDataRowToObject<T>(DataRow row) where T:class,new ()
        {
            if (row == null)
            {
                return default(T);
            }

            T model = (T)Activator.CreateInstance(typeof(T));

            for (int i = 0; i < row.Table.Columns.Count; i++)
            {
                PropertyInfo propertyInfo = model.GetType().GetProperty(row.Table.Columns[i].ColumnName);

                try
                {
                    if (propertyInfo != null && row[i] != DBNull.Value)
                        propertyInfo.SetValue(model, row[i], null);
                    else continue;

                }
                catch
                {
                    return null;
                }
               
            }
            return model;
        }

        public  T CopySameFieldsObject<T>(Object source)
        {
            Type srcT = source.GetType();
            Type destT = typeof(T);

            // 构造一个要转换对象实例
            Object instance = destT.InvokeMember("", BindingFlags.CreateInstance, null, null, null);

            // 这里指定搜索所有公开和非公开的字段
            FieldInfo[] srcFields = srcT.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            // 将源头对象的每个字段的值分别赋值到转换对象里，因为假定字段都一样，这里就不做容错处理了
            foreach (FieldInfo field in srcFields)
            {
                destT.GetField(field.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).
                    SetValue(instance, field.GetValue(source));
            }

            return (T)instance;
        }


    }
}
